package stark.app.function.playphone;

import android.os.Build;

import com.blankj.utilcode.constant.TimeConstants;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.stark.playphone.lib.GlobalConfig;
import com.stark.playphone.lib.LockDataManager;
import com.stark.playphone.lib.LockService;
import com.stark.playphone.lib.PpConst;
import com.stark.playphone.lib.WhiteAppManager;
import com.stark.playphone.lib.data.DataProvider;
import com.stark.playphone.lib.db.LockDataForDay;
import com.stark.playphone.lib.db.LockRecDbHelper;
import com.stark.playphone.lib.db.LockTask;
import com.stark.playphone.lib.db.LockTaskDbHelper;
import com.stark.playphone.lib.db.LockType;

import java.util.List;

import stark.app.R;
import stark.app.databinding.ActivityPlayPhoneDemoBinding;
import stark.common.basic.base.BaseNoModelActivity;
import stark.common.basic.utils.PermissionUtil;
import stark.common.basic.utils.TimeUtil;

/**
 * Author：daizhongbin on 2022/8/18
 * Email：1027154338@qq.com
 * Desc:
 */
public class PlayPhoneDemoActivity extends BaseNoModelActivity<ActivityPlayPhoneDemoBinding> {

    @Override
    protected int onCreate() {
        return R.layout.activity_play_phone_demo;
    }

    @Override
    protected void initView() {
        mDataBinding.btnSimpleLock.setOnClickListener(v -> {
            if (hasPermission()) {
                LockTask task = createSimpleTask();
                LockTaskDbHelper.insert(task);
                LockService.startTask(this, task);
            }
        });
        mDataBinding.btnOneLock.setOnClickListener(v -> {
            if (hasPermission()) {
                LockTask task = createOneTimeTask();
                LockTaskDbHelper.insert(task);
                LockService.startTask(this, task);
            }
        });
        mDataBinding.btnRecycleLock.setOnClickListener(v -> {
            if (hasPermission()) {
                LockTask task = createRecycleTask();
                LockTaskDbHelper.insert(task);
                LockService.startTask(this, task);
            }
        });
        mDataBinding.btnTimingLock.setOnClickListener(v -> {
            if (hasPermission()) {
                LockTask task = createTimingTask();
                LockTaskDbHelper.insert(task);
                ToastUtils.showShort("已添加定时锁机任务");
            }
        });
        mDataBinding.btnGlobal.setOnClickListener(v -> {
            GlobalConfig.getInstance().setPersonalText("你好锁机");
            //设置背景音乐
            GlobalConfig.getInstance().setBgmBean(DataProvider.getBgmList().get(3));
            //设置主题
            GlobalConfig.getInstance().setThemeBean(DataProvider.getThemeList().get(3));
            //拿起手机是否报警 内部功能暂未实现，待完善
            GlobalConfig.getInstance().setPhoneRaiseAlert(true);
        });
        mDataBinding.btnCustom.setOnClickListener(v -> {
            //通过该方法设置你自己想要的悬浮窗界面，这里只是告诉你用下面这个方法来实现，这个方法最好在Application的子类的onCreate方法中实现
            //LockService.setCustomLockFloatView(null);
        });
        mDataBinding.btnWhiteName.setOnClickListener(v -> {
            final String wechat = "com.tencent.mm";
            //添加白名单
            WhiteAppManager.getInstance().addApp(wechat);
            //删除白名单
            //WhiteAppManager.getInstance().removeApp(wechat);
        });
        mDataBinding.btnGetTotalCount.setOnClickListener(v -> {
            int totalLockCount = LockDataManager.getInstance().getTotalLockCount();
            int totalForceExitCount = LockDataManager.getInstance().getTotalForceExitCount();
            long totalLockDuration = LockDataManager.getInstance().getTotalLockDuration();
            totalLockDuration = totalLockDuration / TimeConstants.MIN;  //转换为分钟
            mDataBinding.tvDataRet.setText("总锁机次数：" + totalLockCount + ", 总强制退出次数：" +
                    totalForceExitCount + ", 总锁机时长：" + totalLockDuration + " 分钟");
        });
        mDataBinding.btnRecentDayData.setOnClickListener(v -> {
            //获取最近7天的数据
            List<LockDataForDay> dataForDayList = LockRecDbHelper.getLockDataForDays(7);
            StringBuilder builder = new StringBuilder();
            for (LockDataForDay dataForDay : dataForDayList) {
                builder.append(TimeUtils.millis2String(dataForDay.startTime, "MM月dd日"));
                builder.append(" 锁机次数为：" + dataForDay.getLockCount());
                builder.append(" 锁机时长为：" + (dataForDay.getLockDuration() / TimeConstants.MIN) + "分钟");
                builder.append("\n");
            }
            mDataBinding.tvDataRet.setText(builder.toString());
        });
        mDataBinding.btnListenEnd.setOnClickListener(v -> {
            LockService.setListener(new LockService.IListener() {
                @Override
                public void onLockEnd() {
                    ToastUtils.showShort("锁机结束了");
                }
            });
        });
    }

    @Override
    protected void initData() {

    }

    private boolean hasPermission() {
        if (!PermissionUtil.hasUsageStatsPermission()) {
            PermissionUtil.reqUsageStatsPermission(this, 1);
            return false;
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (!PermissionUtils.isGrantedDrawOverlays()) {
                PermissionUtils.requestDrawOverlays(null);
                return false;
            }
        }
        return true;
    }

    private LockTask createSimpleTask() {
        LockTask task = new LockTask();
        task.lockType = LockType.SIMPLE;
        task.name = "1分钟";
        task.lockDuration = TimeConstants.MIN;
        return task;
    }

    private LockTask createOneTimeTask() {
        LockTask task = new LockTask();
        task.lockType = LockType.SINGLE;
        task.name = "1分钟";
        task.lockDuration = TimeConstants.MIN;
        return task;
    }

    private LockTask createRecycleTask() {
        LockTask task = new LockTask();
        task.lockType = LockType.RECYCLE;
        task.name = "多次1分钟";
        task.lockDuration = TimeConstants.MIN;
        task.interval = TimeConstants.MIN;  //间隔1分钟
        task.repeatCount = 3;   //循环3次
        return task;
    }

    private LockTask createTimingTask() {
        LockTask task = new LockTask();
        task.lockType = LockType.TIMING;
        task.name = "定时任务";
        long now = System.currentTimeMillis();
        task.lockTime = now - TimeUtil.getStartOfOneDay(now) + 10 * TimeConstants.SEC;  //锁机开始时间为你点击的此刻的后10秒
        task.lockDuration = TimeConstants.HOUR; //锁机时长1小时
        task.weekFlag = PpConst.FLAG_WEEK_1 |
                PpConst.FLAG_WEEK_2 |
                PpConst.FLAG_WEEK_3 |
                PpConst.FLAG_WEEK_4 |
                PpConst.FLAG_WEEK_5 |
                PpConst.FLAG_WEEK_6 |
                PpConst.FLAG_WEEK_7;    //每天都执行该定时任务
        task.isActive = true;       //激活
        return task;
    }
}
